package com.itchu.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 *      这个类主要是做未登录用户无权限登录访问资源的返回的异常处理
 *      到时主要是返回到登录页面的处理
 */
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        // 如果认证失败就返回错误信息
        // 设置返回的编码格式，防止乱码
        response.setContentType("application/json;charset=utf-8");
        // 401错误
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 以字符输出流响应回去
        PrintWriter out = response.getWriter();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", HttpServletResponse.SC_UNAUTHORIZED);
        map.put("message", "您未登录！");
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }
}
